<template>
  <div class="profile-page">
    <!-- 用户信息头部 -->
    <div class="user-profile-header">
      <div class="user-info">
        <div class="avatar-container">
          <div class="avatar-wrapper">
            <img v-if="user.avatar" :src="processImageUrl(user.avatar)" alt="头像" class="avatar">
            <div v-else class="avatar-default">
              {{ user.nickName ? user.nickName.substring(0, 1).toUpperCase() : 'U' }}
            </div>
            <div class="avatar-edit-overlay" @click="handleAvatarClick">
              <span class="edit-text">更换头像</span>
            </div>
          </div>
        </div>
        <div class="user-text">
          <div class="nickname">{{ user.nickName || '未设置昵称' }}</div>
          <div class="user-account">账号：{{ user.userName || '未登录' }}</div>
        </div>
      </div>
      <div class="profile-edit-btn" @click="goToUserDetail">
        <span>编辑资料</span>
        <svg-icon icon-class="right"/>
      </div>

      <!-- 隐藏的文件上传输入 -->
      <input
        ref="avatarInput"
        accept="image/*"
        style="display: none"
        type="file"
        @change="onAvatarChange"
      />
    </div>

    <!-- 功能列表区域 - 可滚动部分 -->
    <div class="menu-scroll-container">
      <!-- 账号管理 -->
      <div class="menu-group">
        <div class="group-title">账号管理</div>
        <div class="menu-flex">
          <div
            v-for="(item, index) in accountItems"
            :key="'account-'+index"
            class="menu-flex-item"
            @click="navigateTo(item.path)">
            <div class="flex-icon">
              <svg-icon :icon-class="item.icon"/>
            </div>
            <div class="flex-text">{{ item.title }}</div>
          </div>
        </div>
      </div>

      <!-- 功能列表 -->
      <div class="menu-group">
        <div class="group-title">常用功能</div>
        <div class="menu-list">
          <div
            v-for="(item, index) in featureItems"
            :key="'feature-'+index"
            class="menu-item"
            @click="item.click()">
            <div class="item-left">
              <div class="item-icon">
                <svg-icon :icon-class="item.icon"/>
              </div>
              <span class="item-text">{{ item.title }}</span>
            </div>
            <svg-icon class="item-arrow" icon-class="right"/>
          </div>

        </div>
      </div>

      <!-- 设置与帮助 -->
      <div class="menu-group">
        <div class="group-title">设置与帮助</div>
        <div class="menu-list">
          <div
            v-for="(item, index) in settingItems"
            :key="'setting-'+index"
            class="menu-item"
            @click="navigateTo(item.path)">
            <div class="item-left">
              <div class="item-icon">
                <svg-icon :icon-class="item.icon"/>
              </div>
              <span class="item-text">{{ item.title }}</span>
            </div>
            <svg-icon class="item-arrow" icon-class="right"/>
          </div>
        </div>
      </div>

      <!-- 退出登录 -->
      <div class="logout-wrapper">
        <button class="logout-btn" @click="logout">退出登录</button>
      </div>
    </div>
    <ModernModal ref="gameDialog" :show-footer="false" title="游戏切换" type="success">
      <div v-if="gameLoading" style="text-align: center">
        <i class="el-icon-loading"/>
      </div>
      <el-radio-group v-model="user.gameId" class="game-switch" @change="switchGame()">
        <el-radio v-for="item in gameList" :key="item.id" :aria-hidden="false" :label="item.id" class="gameItem">
          {{ item.gameName }}
        </el-radio>
      </el-radio-group>
    </ModernModal>

    <ModernModal ref="passwordDialog" :show-footer="false" title="修改密码" type="success">
      <reset-pwd/>
    </ModernModal>
  </div>
</template>

<script>
import {getUserProfile, updateUserProfile, uploadAvatar} from "@/api/system/user";
import {list} from "@/api/game/game"
import ModernModal from "@/components/Dialog"
import resetPwd from "@/views/system/user/profile/resetPwd"
import store from "@/store";
import {isRelogin} from "@/utils/request";

export default {
  name: 'UserProfile',
  components: {
    ModernModal, resetPwd
  },
  data() {
    return {
      user: {},
      gameList: [],
      gameLoading: false,
      roleGroup: {},
      postGroup: {},
      activeTab: "userinfo",
      accountItems: [
        {title: '余额充值', icon: 'balance', path: '/mobile/personal-info'},
        {title: '我的工单', icon: 'tickets', path: '/mobile/security'},
        {title: '消息通知', icon: 'wx', path: '/mobile/address'}
      ],
      featureItems: [
        {
          title: '个人资料', icon: 'person-info', click: () => {
          }
        },
        {
          title: '游戏切换', icon: 'game2', click: () => {
            this.$refs.gameDialog.open();
            this.getGameList()
          }
        },
        {title: '修改密码', icon: 'password', click: () => this.$refs.passwordDialog.open()}
      ],
      settingItems: [
        {title: '意见反馈', icon: 'edit', path: '/mobile/feedback'}
      ]
    }
  },

  created() {
    this.getUser();
  },
  methods: {
    // 处理图片URL，判断是否需要添加前缀
    processImageUrl(url) {
      if (!url) return '';

      // 如果是本地预览的blob URL或者已经是完整URL，直接返回
      if (url.startsWith('blob:') || url.startsWith('http://') || url.startsWith('https://')) {
        return url;
      }

      // 否则添加API前缀
      return `${process.env.VUE_APP_BASE_API}/${url}`;
    },
    getUser() {
      getUserProfile().then(response => {
        this.user = response.data;
        this.roleGroup = response.roleGroup;
      });
    },
    goToUserDetail() {
      this.$router.push('/info');
    },
    navigateTo(path) {
      this.$router.push(path);
    },
    getGameList() {
      this.gameLoading = true
      list().then(res => {
        this.gameLoading = false
        this.gameList = res.data
      })
    },
    switchGame() {
      this.$refs.gameDialog.close()
      updateUserProfile(this.user).then(res => {

      })
    },
    logout() {
      this.$dialog.confirm({
        title: '退出提示',
        type: 'warning',
        content: '是否确认退出登录？',
        confirmText: '退 出',
        cancelText: '取 消'
      }).then((confirm) => {
        if (confirm) {
          isRelogin.show = false;
          store.dispatch('LogOut').then(() => {
            location.href = '/index';
          })
        }
      }).catch(() => {
      })
    },
    // 头像点击处理
    handleAvatarClick() {
      // 触发文件选择
      this.$refs.avatarInput.click();
    },
    // 头像文件变更处理
    onAvatarChange(e) {
      const file = e.target.files[0];
      if (!file) return;

      // 验证文件类型
      if (!file.type.match('image.*')) {
        this.$message.error('请选择图片文件');
        return;
      }

      // 验证文件大小（限制为2MB）
      if (file.size > 2 * 1024 * 1024) {
        this.$message.error('图片大小不能超过2MB');
        return;
      }

      // 创建预览
      const reader = new FileReader();
      reader.onload = (e) => {
        // 这里可以先预览图片
        const previewUrl = e.target.result;

        // 在实际应用中，这里应该调用上传API
        this.uploadImg(file, previewUrl);
      };
      reader.readAsDataURL(file);
    },
    // 上传头像
    uploadImg(file, previewUrl) {
      // 创建FormData对象用于上传
      const formData = new FormData();
      formData.append('avatarfile', file);
      uploadAvatar(formData).then(res => {
        console.log(res)
        // 临时显示预览
        this.user.avatar = res.imgUrl;
        store.commit('SET_AVATAR', this.user.avatar);
        this.$message.success('头像更新成功');
      }).catch(() => {
        this.$message.error('头像上传失败');
      });
    }
  }
}
</script>

<style scoped>
.profile-page {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}
/* 用户信息头部 */
.user-profile-header {
  background: linear-gradient(to right, #4a90e2, #5a9cf1);
  padding: 25px 16px 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-shadow: 0 2px 10px rgba(74, 144, 226, 0.5);
  position: relative;
  flex-shrink: 0; /* 防止头部被压缩 */
}

.user-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}

/* 优化后的头像容器 */
.avatar-container {
  position: relative;
  margin-bottom: 15px;
  width: 80px;
  height: 80px;
}

.avatar-wrapper {
  width: 100%;
  height: 100%;
  position: relative;
  cursor: pointer;
  border-radius: 50%;
  overflow: hidden;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;
}

.avatar-wrapper:hover {
  transform: scale(1.05);
}

.avatar, .avatar-default {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  border: 3px solid rgba(255, 255, 255, 0.8);
}

.avatar {
  object-fit: cover;
}

.avatar-default {
  background-color: #ffffff;
  color: #4a90e2;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 32px;
  font-weight: bold;
}

/* 头像编辑覆盖层 */
.avatar-edit-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 40%;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.avatar-wrapper:hover .avatar-edit-overlay {
  opacity: 1;
}

.camera-icon {
  font-size: 16px;
  margin-bottom: 2px;
}

.edit-text {
  font-size: 10px;
  font-weight: 500;
}

.user-text {
  text-align: center;
}

.nickname {
  font-size: 18px;
  font-weight: 500;
  color: #ffffff;
  margin-bottom: 4px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.user-account {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.9);
}

.profile-edit-btn {
  position: absolute;
  right: 16px;
  top: 16px;
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 15px;
  padding: 4px 10px;
  display: flex;
  align-items: center;
  color: #ffffff;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.profile-edit-btn:hover {
  background-color: rgba(255, 255, 255, 0.3);
  transform: translateX(-3px);
}

.profile-edit-btn svg-icon {
  margin-left: 4px;
  font-size: 12px;
}

/* 可滚动的菜单容器 */
.menu-scroll-container {
  flex: 1;
  overflow-y: auto;
  padding: 15px 12px;
}

.menu-group {
  margin-bottom: 15px;
}

.group-title {
  font-size: 9px;
  color: #999999;
  padding: 8px 4px 8px;
  font-weight: 500;
}

/* 弹性布局的菜单项 - 自动适应数量 */
.menu-flex {
  display: flex;
  flex-wrap: wrap;
  background-color: #ffffff;
  border-radius: 10px;
  padding: 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.menu-flex-item {
  flex: 1;
  min-width: 25%; /* 确保至少有4个一行 */
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px 5px;
  cursor: pointer;
  transition: transform 0.3s ease, background-color 0.3s ease;
}

.menu-flex-item:hover {
  transform: translateY(-3px);
  background-color: rgba(74, 144, 226, 0.05);
}

.flex-icon {
  width: 40px;
  height: 40px;
  background-color: rgba(74, 144, 226, 0.1);
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 8px;
  transition: background-color 0.3s ease;
}

.menu-flex-item:hover .flex-icon {
  background-color: rgba(74, 144, 226, 0.2);
}

.flex-icon svg-icon {
  font-size: 20px;
  font-weight: bold;
  color: #4a90e2;
}

.flex-text {
  font-size: 12px;
  color: #333333;
  text-align: center;
}

/* 列表样式 */
.menu-list {
  background-color: #ffffff;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.menu-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 14px 16px;
  border-bottom: 0.5px solid #f2f2f2;
  cursor: pointer;
  transition: background-color 0.3s ease, padding-left 0.3s ease;
}

.menu-item:hover {
  background-color: rgba(74, 144, 226, 0.05);
  padding-left: 20px;
}

.menu-item:last-child {
  border-bottom: none;
}

.item-left {
  display: flex;
  align-items: center;
}

.item-icon {
  width: 24px;
  height: 24px;
  background-color: rgba(74, 144, 226, 0.1);
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 12px;
  transition: background-color 0.3s ease;
}

.menu-item:hover .item-icon {
  background-color: rgba(74, 144, 226, 0.2);
}

::v-deep .svg-icon {
  margin: 0 !important;
}

.item-icon ::v-deep .svg-icon {
  font-size: 14px;
  color: #4a90e2;
}

.item-text {
  font-size: 12px;
  color: #333333;
}

.item-arrow {
  font-size: 12px;
  color: #cccccc;
  transition: transform 0.3s ease;
}

.menu-item:hover .item-arrow {
  transform: translateX(3px);
  color: #4a90e2;
}

/* 退出登录按钮 */
.logout-wrapper {
  margin-top: 20px;
  margin-bottom: 10px;
}

.logout-btn {
  width: 100%;
  height: 44px;
  background-color: #ffffff;
  border: none;
  border-radius: 10px;
  color: #ff3b30;
  outline: none;
  font-size: 14px;
  font-weight: 400;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  cursor: pointer;
  transition: background-color 0.3s ease, transform 0.3s ease;
}

.logout-btn:hover {
  background-color: #fff0f0;
  transform: translateY(-2px);
}

.logout-btn:active {
  background-color: #f9f9f9;
  transform: translateY(0);
}

.game-switch {
  display: flex;
  flex-direction: column;
}

.gameItem {
  margin: 10px !important;
}
</style>
